var fs = require('fs');
var request = require("superagent");
var Excel = require('exceljs');

var num = 10;

// 任务创建间隔（ms）
var interval = 5000;

var source = 'https://m.ly.com/member/order/getlist';

fs.readFile('cookie.ini', 'utf-8', function (err, data) {
    if (err) {
        console.error(err);
    } else {
        if (data.length > 10) {
            startRequest(source, data, num);
        } else {
            console.log('请设置Cookie文件');
        }
    }
});

var workbook = new Excel.Workbook();

var ws1 = workbook.addWorksheet("订单信息");
ws1.columns = [
    {header: '项目', width: 10},
    {header: '航班信息', width: 45},
    {header: '金额', width: 10},
    {header: '日期', width: 35},
    {header: '下单时间', width: 20},
    {header: '订单号', width: 25},
    {header: '订单状态', width: 10},
    {header: '票面', width: 30},
    {header: '合计', width: 10},
    {header: '明细', width: 40},
    {header: '机型', width: 20},
    {header: '航空公司', width: 15},
    {header: '舱等', width: 10},
    {header: '乘机人', width: 25}
];

var n = 0;
var pageSize = 10;
var item = [];
var offset = 0;
item['jiudian'] = '酒店';
item['guoneijipiao'] = '国内机票';

function startRequest(url, cookie, num) {
    console.log('初始化系统');
    for (var j = 1; j <= Math.ceil(num / 10); j++) {
        setTimeout(function (j) {
            console.log('创建任务' + j);
            request.post(url)
                .set("Cookie", cookie)
                .type('form')
                .send({
                    PageSize: pageSize,
                    PageIndex: j,
                    projectTag: ''
                })
                .end(function (err, res) {
                    if (err) {
                        console.log("error: " + err);
                        workbook.xlsx.writeFile(num + ' - export.xlsx')
                            .then(function () {
                                console.log('Saved');
                            });

                        process.exit(0);
                    } else {
                        var resJson = JSON.parse(res.text);
                        if (resJson.Success !== undefined) {
                            if (resJson.Message === '请先登录') {
                                console.log('Cookie不可用，请更新')
                            } else {
                                console.log(resJson.Message);
                            }

                            process.exit(0);
                        }
                        var resBody = resJson.response.body;
                        // 限制要获取的订单数量，不得超过总订单数
                        if (num > resBody.pageInfo.totalCount) {
                            num = resBody.pageInfo.totalCount;
                            console.log('将要获取的订单数量已被更改为：' + num);
                        }
                        console.log('订单总数：' + resBody.pageInfo.totalCount + ' - 总页数：' + resBody.pageInfo.totalPage + ' - 当前页：' + resBody.pageInfo.page + ' - 页数量：' + resBody.pageInfo.pageSize);

                        offset += pageSize - resBody.orderListAll.length;

                        for (var i = 0; i < resBody.orderListAll.length; i++) {
                            var buffer = resBody.orderListAll[i];

                            if (buffer.projectTag === 'guoneijipiao') {
                                getPassenger(buffer);
                            } else {
                                offset++;
                                // ws1.addRow([item[buffer.projectTag], buffer.title, buffer.amount, buffer.firstDesc, buffer.orderCreateTime, buffer.orderId, buffer.orderStatus]);
                            }
                        }
                    }
                });
        }, interval * j, j);
    }
}

function getInfo(buffer, airplaneModel, airwaysName, cabinName, name) {
    console.log('订单：' + buffer.orderId + ' --- OK');
    request.post('https://wx.17u.cn/flightorderdetail/order/orderdetailfeenew')
        .set("tcsectoken", '027093039245106135243230197030056045202015212082190244053038211091054223246238095172074148068195091131052177225139141156068169107072219105044138127221143226198081138003204059159017138172156242009162017104101250028125070084005152049053241031101057237207048010011057028115206203246093081221209059155243085132183181')
        .type('form')
        .send({
            IsMuilteSite: 1,
            MemberId: "289184525",
            airlineType: 1,
            originMemberId: "ZGG1clqLuvz9a0fh79ngPw==",
            plat: 518,
            serialNo: buffer.orderId
        })
        .end(function (err, res) {
            n++;

            if (err) {
                console.log(err);

                process.exit(0);
            } else {
                var resJson = JSON.parse(res.text);

                if (resJson.body.errCode !== 0) {
                    console.log(resJson.body.errMsg + '，请重新获取 tcsectoken');

                    process.exit();
                }

                var fee = resJson.body.transInfos[0].segments[0].itemDetails;
                var lastFee = 0;
                var lastItemName = '';
                var detail = '';
                for (var i = 0; i < fee.length; i++) {
                    lastFee += fee[i].itemUnitPrice * fee[i].itemNums;
                    lastItemName += fee[i].itemName + '(' + fee[i].itemUnitPrice + 'x' + fee[i].itemNums + ')';

                    for (var j = 0; j < fee[i].subItems.length; j++) {
                        detail += fee[i].subItems[j].subItemName + '(' + fee[i].subItems[j].subItemPrice + 'x' + fee[i].subItems[j].subItemNums + ')';
                    }
                }

                ws1.addRow([item[buffer.projectTag], buffer.title, buffer.amount, buffer.firstDesc, buffer.orderCreateTime, buffer.orderId, buffer.orderStatus, lastItemName, lastFee, detail, airplaneModel, airwaysName, cabinName, name]);
            }

            if (n + offset >= num) {
                workbook.xlsx.writeFile(num + ' - export.xlsx')
                    .then(function () {
                        console.log('OK: ' + num + ' - export.xlsx');
                    });
            }
        })
}

function getPassenger(buffer) {
    request.post('https://wx.17u.cn/flightorderdetail/order/orderdetailinfo')
        .set("tcsectoken", '027093039245106135243230197030056045202015212082190244053038211091054223246238095172074148068195091131052177225139141156068169107072219105044138127221143226198081138003204059159017138172156242009162017104101250028125070084005152049053241031101057237207048010011057028115206203246093081221209059155243085132183181')
        .type('form')
        .send({
            IsMuilteSite: 1,
            banner: "2.0.0",
            isFromGuolv: false,
            plat: 518,
            serialNo: buffer.orderId
        })
        .end(function (err, res) {
            if (err) {
                console.log(err);

                process.exit();
            } else {
                var resJson = JSON.parse(res.text);
                if (resJson.resCode !== 0) {
                    console.log('订单号：' + buffer.orderId + '乘客信息获取失败');

                    process.exit();
                } else {
                    var airplaneModel = resJson.body.segments[0].airplaneModel;
                    var airwaysName = resJson.body.segments[0].saleAirways.airwaysName;
                    var cabinName = resJson.body.segments[0].saleAirways.cabinName;
                    var passenger = resJson.body.segments[0].passengers;

                    var name = '';
                    for (var i = 0; i < passenger.length; i++) {
                        name += passenger[i].passengerName + ' ';
                    }

                    getInfo(buffer, airplaneModel, airwaysName, cabinName, name);
                }
            }
        })
}
